import to from "await-to-js";
import { forIn, sortBy } from "lodash";

import { handleFlightsParams, TimeoutGetData, job } from "./handle";
import { ScheduleType, WorkSpaceParams } from "./store/models";
import { workerDispatch } from "./workerQueue";

import { openDB } from "~/utils/DataCache";
import eventBus from "~/utils/event";
export const RawWorkSpaceState: {
  flights: string[];
  workSpace: any;
  startTime: string;
  endTime: string;
} = {
  flights: [],
  workSpace: {},
  startTime: "",
  endTime: "",
};
export const axisData: { data: string[]; offsetAxisData: string[] } = {
  data: [],
  offsetAxisData: [],
};
export const Scheduler: ScheduleType = {
  db: null,
  datas: {},
  alreadyQueue: [],
  alreadyComplete: [],
  timer: null,
  timeout: 20000,
  startTime: 0,
  loading: false,
  init: (): void => {
    Scheduler.loading = true;
    Scheduler.datas = {};
    Scheduler.alreadyComplete = [];
    Scheduler.alreadyQueue = [];
    Scheduler.startTime = 0;
    workerDispatch.startWorkers(job);
  },
  clear: (): void => {
    console.log(`clear queue`);
    // Scheduler.datas = {};
    Scheduler.alreadyQueue = [];
    Scheduler.alreadyComplete = [];
    workerDispatch.clearQueue();
    clearInterval(Scheduler.timer);
  },
  get: async (workSpaceParams: WorkSpaceParams): Promise<any> => {
    Scheduler.init();
    const [err, db] = await to(openDB("chartData"));
    if (err) {
      console.log("open indexed db error", err);
    }
    Scheduler.db = db;
    return new Promise(async (resolve, reject) => {
      eventBus.once(`queueComplete`, () => {
        // forIn(Scheduler.datas, (value, key) => {
        // _.forEach(value, (item: any, index) => {
        //   if (item[key] === "") {
        //     item[key] = "";
        //     item.systime = null;
        //   }
        // });
        // Scheduler.datas[key] = sortBy(value, "systime");
        // Scheduler.datas[key] = value;
        // });
        Scheduler.loading = false;
        return resolve({ queue: "queue" });
      });
      const noexist = handleFlightsParams(workSpaceParams);
      TimeoutGetData(workSpaceParams, noexist);
    });
  },
};
